# encoding=utf-8
"""
响应对象业务校验
"""
from pyquery import PyQuery
from scrapy.exceptions import IgnoreRequest
from zc_core.middlewares.validate import BaseValidateMiddleware
from zc_core.util.http_util import retry_request


class BizValidator(BaseValidateMiddleware):

    def validate_sku(self, request, response, spider):
        return response

    def validate_price(self, request, response, spider):
        if not response.text:
            return retry_request(request)
        if response.status == 500 and response.text:
            raise IgnoreRequest('异常[Price]：[%s]' % request.meta.get('skuId'))

        return response

    def validate_item(self, request, response, spider):
        if not response.text:
            return retry_request(request)
        if response.status == 500 and response.text and '网路延迟，请关闭页面' in response.text:
            raise IgnoreRequest('异常[Item]：[%s]' % request.meta.get('skuId'))
        # 下架校验
        jpy = PyQuery(response.text)
        state = jpy('input#goodsState').attr('value')
        if not state or state.strip() != '00052_1':
            raise IgnoreRequest('下架[Item]：[%s]' % request.meta.get('skuId'))

        return response
